import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig,  AxiosResponse} from 'axios'
import { ElLoading } from 'element-plus'
// request.js
// 创建新的axios实例
const service: AxiosInstance = axios.create({
    // 环境变量，需要在.env文件中配置
    baseURL: '',
    // 超时时间暂定5s
    timeout: 5000,
    withCredentials: true,// 异步请求携带cookie
  });
  
let loadingInstance = null;
function closeLoading(){
    if(loadingInstance && loadingInstance.close){
        loadingInstance.close();
        loadingInstance = null;
    }
}

  // 请求拦截器
service.interceptors.request.use(
    (config) => {
      // 可以在这里添加请求头等信息
    //   console.log(config);
      
      let { needLoading } = config.data || {};
      if(needLoading){
          loadingInstance = ElLoading.service({
            background: 'transparent',
            text: 'loading...'
          })
          delete config.data.needLoading
      }
      
      
      return config;
    },
    (error: any) => {
      // 请求错误处理
      closeLoading();
      return Promise.reject(error);
    }
  );
   
  // 响应拦截器
  service.interceptors.response.use(
    (response: AxiosResponse) => {
      // 对响应数据做处理，例如只返回data部分
      closeLoading();
      return response.data;
    },
    (error: any) => {
      // 响应错误处理
      closeLoading();
      return Promise.reject(error);
    }
  );

  export const jsonPost = (api, ajaxData?, otions?)=> {
    

    return service.post(api,ajaxData,{
        ...(otions || {}),
        headers:{
            Accept: 'application/json;charset=UTF-8'
        },
       
    })
  }

  export const reqGet = (api, ajaxData?)=> {

    return service.get(api,ajaxData)
  }

  export const formPost = (api, ajaxData?, otions?)=> {
    

    return service.post(api,ajaxData,{
        ...(otions || {}),
        headers:{
            'Content-type':'application/x-www-form-urlencoded',
            Accept: 'application/json;charset=UTF-8',

        },
       
    })
  }

  export default service;